<?php
	App::import("Model","Config.Config");
	class DatabaseConfig extends Config
	{
		var $name = "DatabaseConfig";
		var $useTable = false;
		//@todo this should be in field Properties
		var $validate = array("host"=>VALID_NOT_EMPTY,'login'=>VALID_NOT_EMPTY,'database'=>VALID_NOT_EMPTY);
		function save($config,$importDb = true, $initalData = true,$mergeOld = true)
		{
			/* commenting initial data support because it requires more testing
			if(isset($config['DatabaseConfig']['initial_data']) && $config['DatabaseConfig']['initial_data'] == 0)
			{
				$initalData = false;  // for installer option
			}*/
			$configToSave = array("Database"=>$config[$this->alias]);
			$return =  parent::save($configToSave,CONFIG_FILE, $importDb , array() ,$mergeOld );
			if($return == true && $importDb && $initalData)
			{
				$this->importIntialData();
			}
        App::import('Model','Cms.EmailTemplate');
        $EmailTemplate = new EmailTemplate(false,null,'temp');
        $EmailTemplate->resetEmailTemlates(WWW_ROOT.'files',cr('emailConfig.Buttonset'),cr('emailConfig.MailConfiguration'));	
			return $return;
		}
		
		private function importIntialData()
		{
			$intialDataFile = APP.'config'.DS.'sql'.DS.'initial_data.sql';
			if(file_exists($intialDataFile))
			{
				Utility::importSqlFile($intialDataFile, true,'temp');
			}
			//use to insert inital Data
			callHooks("InsertInitalDataHook",'.+',$this,'temp');		
		}
		function initialize()
		{	
			$this->fieldProperties = array(
	
				'host'=> array('label'=> __('Host'),
							 'after' => __('Enter name of your DB host. Usually "localhost".'),
							 'validate'=>VALID_NOT_EMPTY,'group'=>"setup"),
				'login' => array('label'=> __('DB User'),
								 'after' => __('Enter your MySQL DB username.'),
								 'validate'=>VALID_NOT_EMPTY,'group'=>"setup"),
				
				'password'=> array('label'=> __('Password'),
								 'after' => __('Enter password of username above.'),
								 'type'=>'password','group'=>"setup"),
				
				'database'=> array('label'=> __('Database'),
								 'after' => __('Your database name.'),
								 'validate'=>VALID_NOT_EMPTY,'group'=>"setup")

			);
			if(cr("configs.DatabaseConfig.properties"))
			{
				$allowedProperty = array('label','tooltip','after','before','validate','required');
				$allowedPropertyArray = array_combine($allowedProperty, $allowedProperty);
				$fields = $this->getFields();
				foreach(cr("configs.DatabaseConfig.properties") as $field=> $properties)
				{
					if(!in_array($field,$fields))
					{
						continue;
					}
					$properties = array_intersect_key($properties, $allowedPropertyArray);
					$this->setFieldProperties($field, $properties);
				}
			}
			/*
			if(!Installer::isInstalled())
			{
				$this->fieldProperties['initial_data'] = array(
					'label'=>__("Insert demo data"),
					'type'=>"checkbox",
					'group' => 'setup',
					'after'=>__("Install demo data to understand functionality and play with different features * recommended *")
				);
			}*/
			parent::initialize();
		}
		private function selectDatabase($dbData)
		{
			$dbName = $dbData['database'];
			$dbSelected = mysql_select_db($dbName);
			if($dbSelected == false)
			{
				$createQuery =	"CREATE DATABASE ".$dbName;
				if(mysql_query($createQuery) !== false)
				{
					$dbSelected = true;
				}else
				{
					$dbSelected = mysql_select_db($dbName);
				}
			}
			return $dbSelected;
		}
		protected  function validateConnection($connectionInfo)
		{
			$return = false;
			$link = @mysql_connect($connectionInfo['host'], $connectionInfo['login'], $connectionInfo['password']);
			if($link !== false)
			{
				$this->testLink = $link;
				$return = true;
			}
			return $return;
		}
		private function validateDatabaseConnection()
		{
			$connection = $this->validateConnection($this->data[$this->alias]);
			if($connection !== true)
			{
				$this->invalidate('host',sprintf(__("No connection found: %s"),mysql_error()));
				return false;
			}
			if($this->selectDatabase($this->data[$this->alias]) == false)
			{
				$this->invalidate('database',sprintf(__("Cannot select or create database: %s."),mysql_error()));
				return false;
			}
			return true;
		}
		
		function validates($options = array())
		{
			$validate = parent::validates($options);
			if($validate)
			{
				$validate = $this->validateDatabaseConnection();
			}
			return $validate;
		}
		
		function hasField($field)
		{
			if(is_string($field))
			{
				$return = isset($this->fieldProperties[$field]);	
			}else
			{
				$return  = parent::hasField($field);
			}
			return $return;
		}
		/**
		 * Hack to prevent mysql connect.
		 */
		function schema()
		{
			return array();
		}
		/**
		 * Hack to prevent mysql connect.
		 */
		function getColumnType()
		{
			return null;
		}
	}
?>